package com.scalar.chiptrack.operations.inventoryps.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.io.FileWriter;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;

import com.scalar.ScalarException;
import com.scalar.chiptrack.db.DataSource;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.inventoryps.forms.InventoryPackingSlipForm;
import com.scalar.chiptrack.operations.inventoryps.forms.InventoryPackingSlipSearchForm;
import com.scalar.chiptrack.operations.inventoryps.InventoryPackingSlip;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;

import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Location;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.PDFGenerator;
import org.apache.struts.util.MessageResources;


public class InventoryPSDao 
{
	public static String getNextPackingSlipNumber() throws ScalarException 
	{
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String packingSlipNumber = "";
    
        try 
        {
            conn = DataSource.getConnection();
            pstmt = conn.prepareStatement ("SELECT PackingSlip_No FROM Inventory_PackingSlip_Table WHERE [Created_On] = (SELECT MAX([Created_On]) FROM Inventory_PackingSlip_Table )");
        
            rs = pstmt.executeQuery();

            if( rs.next() ) 
            {
            	packingSlipNumber = rs.getString( "PackingSlip_No" );
            }
            
            if( "".equalsIgnoreCase( packingSlipNumber ) )
            {
            	packingSlipNumber = "1000";
            }
            else
            {
            	packingSlipNumber = ( Integer.parseInt( packingSlipNumber ) + 1 ) + "";
            }

        }
        catch (Exception sqle) 
        {
            sqle.printStackTrace();
            throw new ScalarException ( "Could not fetch the Next Inventory Packing Slip Number" );
        }
        finally {
            if (rs != null) {
                try { rs.close(); } catch (SQLException excp)
                {
                    throw new ScalarException("SqlException Occurred ..");
                }
            }
            if (pstmt != null) {
                try { pstmt.close(); } catch (SQLException excp)
                {
                    throw new ScalarException("SqlException Occurred ..");

                }
            }
            if (conn != null) {
                try { conn.close(); } catch (SQLException excp)
                {
                    throw new ScalarException("SqlException Occurred ..");
                }
            }
        }

        return packingSlipNumber;
	}
	
	public static void loadInventoryPackingSlip( InventoryPackingSlipForm inventoryPSForm ) throws ScalarException
	{
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<LotDetails> availableLotList = new ArrayList<LotDetails>();
        LotDetails lotDetail = null;

        try
        {
            conn = DataSource.getConnection();
            
            if ( inventoryPSForm.getPackingSlipId() > 0 )
            {
            	pstmt = conn.prepareStatement( "SELECT PackingSlip_ID, PackingSlip_No, Ship_date, From_Vendor_Id, (SELECT V_Name FROM Vendor V WHERE V.Vendor_ID = From_Vendor_Id ) AS From_Vendor_Name, To_Vendor_ID, (SELECT V_Name FROM Vendor V WHERE V.Vendor_ID = To_Vendor_ID ) AS To_Vendor_Name, WayBill_No, Gross_Weight, No_Of_Boxes, Shipping_Method, Shipping_Account, Status, Spl_Instructions FROM Inventory_PackingSlip_Table WHERE PackingSlip_ID = ?" );
            	pstmt.setInt ( 1 , inventoryPSForm.getPackingSlipId() );
            	rs = pstmt.executeQuery();
            	
                if ( rs.next() != false )
                {
                	inventoryPSForm.setPackingSlipNumber( rs.getString( "PackingSlip_No" ) );
                	inventoryPSForm.setShipDate( rs.getString( "Ship_date" ) );
                	inventoryPSForm.setLocationId( rs.getInt( "From_Vendor_Id" ) );
                	inventoryPSForm.setFromVendorName( rs.getString( "From_Vendor_Name" ) );
                	inventoryPSForm.setToVendorId( rs.getInt( "To_Vendor_ID" ) );
                	inventoryPSForm.setToVendorName( rs.getString( "To_Vendor_Name" ) );
                	inventoryPSForm.setWayBillNo( rs.getString( "WayBill_No" ) );
                	inventoryPSForm.setGrossWeight( rs.getString( "Gross_Weight" ) );
                	inventoryPSForm.setNoOfBoxes( rs.getString( "No_Of_Boxes" ) );
                	inventoryPSForm.setShippingMethod( rs.getString( "Shipping_Method" ) );
                	inventoryPSForm.setShippingAccount( rs.getString( "Shipping_Account" ) );
                	inventoryPSForm.setStatus( rs.getString( "Status" ) );
                	inventoryPSForm.setSplInstructions( rs.getString( "Spl_Instructions" ) );
                }
                rs.close();
                pstmt.close();
                pstmt = null;
            	
            	pstmt = conn.prepareCall( "{call SP_LOAD_INVENTORY_PACKINGSLIP_LOTS(?)}" );
            	pstmt.setInt( 1 , inventoryPSForm.getPackingSlipId() );
            	
            	rs = pstmt.executeQuery();
            	
            	while( rs.next() )
            	{
            		lotDetail = new LotDetails();
            		lotDetail.setChecked( true );
            		lotDetail.setLotId( rs.getInt( "LOT_ID" )+"" );
            		lotDetail.setProcessStepId( rs.getInt( "PROCESSSTEP_ID" )+"" );
            		lotDetail.setLocationId( rs.getInt( "LOCATION_ID" )+"" );
            		lotDetail.setPartNumber( rs.getString( "PART_NUMBER" ) );
            		lotDetail.setLotNumber( rs.getString( "Lot_Number" ) );
            		lotDetail.setFabLotNumber( rs.getString( "Fab_Lot_Number" ) );
            		lotDetail.setWaferQtyIn( rs.getInt( "WAFER_QTY_IN" )+"" );
            		lotDetail.setDieQtyIn( rs.getInt( "QTY_IN" )+"" );
            		lotDetail.setDateIn( rs.getString( "DATE_IN" ) );
            		lotDetail.setVendorName( rs.getString( "VENDOR_NAME" ) );
            		lotDetail.setDateCode( rs.getString( "DATE_CODE" ) );
            		lotDetail.setProcessType( rs.getString( "PS_TYPE" ) );
            		lotDetail.setWaferIds( rs.getString( "WAFER_IDS" ) );
            		lotDetail.setCheckedWaferIdsAsString( rs.getString( "SELECTED_WAFER_IDS" ) );
            		lotDetail.setBinQtyAsString( rs.getString( "BIN_QTY_STR" ) );
            		lotDetail.setLotStatus( rs.getString( "LOT_STATUS" ) );
            		lotDetail.setShipQty( rs.getString( "Ship_Qty" ) );
            		lotDetail.setShipDieQty( rs.getString( "Ship_Die_QTY" ) );
            		availableLotList.add( lotDetail );
            	}
            	
            	inventoryPSForm.setAvailableLotsList( availableLotList );

                // Load the Client & Vendor Address Information
                ClientInfo clientInfo = UserDAO.getClientAddressInfo();
                inventoryPSForm.setClientInfo( clientInfo );
                Vendor fromVendor = VendorDAO.getVendorDetails( inventoryPSForm.getLocationId() );
                Vendor toVendor = VendorDAO.getVendorDetails( inventoryPSForm.getToVendorId() );
                inventoryPSForm.setFromAddress( (Address)((Location)fromVendor.getLocationsList().get( 0 )).getLocationAddress() );
                inventoryPSForm.setToAddress( (Address)((Location)toVendor.getLocationsList().get( 0 )).getLocationAddress() );
            }
        }
        catch(Exception sql)
        {
            sql.printStackTrace();
            throw new ScalarException( "Could not Save Inventory Packing Slip " + inventoryPSForm.getPackingSlipNumber() );
        }
        finally
        {
            if( rs != null)
            {
                try{ rs.close();}catch(SQLException se){}
            }
            if( pstmt != null)
            {
                try{ pstmt.close();}catch(SQLException se){}
            }
            if( conn != null)
            {
                try{ conn.close(); }catch(SQLException se){}
            }
        }
	}

	public static void saveInventoryPackingSlip( InventoryPackingSlipForm inventoryPSForm, User user ) throws ScalarException
	{
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int packingSlipId = -1;
        boolean status = false;

        try
        {
            conn = DataSource.getConnection();
            
            if ( inventoryPSForm.getPackingSlipId() == -1 )
            {
            	pstmt = conn.prepareStatement( "INSERT INTO Inventory_PackingSlip_Table( PackingSlip_No, Ship_date,From_Vendor_id,To_Vendor_Id,WayBill_No ,Gross_Weight,No_Of_Boxes,Shipping_Method,Shipping_Account,Status,Created_By,Spl_Instructions,Created_On) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)" );
            	pstmt.setString ( 1 , inventoryPSForm.getPackingSlipNumber() );
            	pstmt.setString ( 2 , inventoryPSForm.getShipDate() );
            	pstmt.setInt	( 3 , inventoryPSForm.getLocationId() );
            	pstmt.setInt	( 4 , inventoryPSForm.getToVendorId() );
            	pstmt.setString	( 5 , inventoryPSForm.getWayBillNo() );
            	pstmt.setString	( 6 , inventoryPSForm.getGrossWeight() );
            	pstmt.setString	( 7 , inventoryPSForm.getNoOfBoxes() );
            	pstmt.setString	( 8 , inventoryPSForm.getShippingMethod() );
            	pstmt.setString	( 9 , inventoryPSForm.getShippingAccount() );
            	pstmt.setString	( 10, "ISSUED"  );
            	pstmt.setString	( 11, user.getUserId() );
            	pstmt.setString	( 12, inventoryPSForm.getSplInstructions() );
            	pstmt.execute();
            	
                pstmt.close();
                pstmt = null;
                
                pstmt = conn.prepareStatement ( "SELECT @@IDENTITY as PackingSlip_ID" );
                rs = pstmt.executeQuery();

                if ( rs.next() != false )
                {
                	packingSlipId =  rs.getInt ( "PackingSlip_ID" );
                }
                rs.close();
                pstmt.close();
                pstmt = null;
                rs =null;
                
            	inventoryPSForm.setPackingSlipId( packingSlipId );
                
            	pstmt = conn.prepareStatement( "INSERT INTO Inventory_PackingSlip_Lot_Table( PackingSlip_Id, Lot_id, Ship_qty, WaferIds, Status ,Timestamp ) VALUES (?,?,?,?,?,CURRENT_TIMESTAMP)" );
            	for( LotDetails lotDetail:inventoryPSForm.getSelectedLotsList() )
            	{
            		if( lotDetail.isChecked() )
            		{                           
            			pstmt.setInt( 1, packingSlipId );
            			pstmt.setInt( 2, Integer.parseInt( lotDetail.getLotId() ) );
            			pstmt.setInt( 3, Integer.parseInt( lotDetail.getShipQty() ) );
            			pstmt.setString( 4, lotDetail.getCheckedWaferIdsAsString() );
            			pstmt.setString( 5, "ISSUED" );
            			pstmt.addBatch();
            		}
            	}
            	pstmt.executeBatch();
            }
            else
            {
            	pstmt = conn.prepareStatement( "update Inventory_PackingSlip_Table Set Ship_date= ?, WayBill_No= ?, Gross_Weight= ?, No_Of_Boxes= ?, Spl_Instructions= ? , Updated_By = ?, Updated_On = CURRENT_TIMESTAMP WHERE PackingSlip_Id = ? " );
                pstmt.setString(1, inventoryPSForm.getShipDate() );
                pstmt.setString(2, inventoryPSForm.getWayBillNo() );
                pstmt.setString(3, inventoryPSForm.getGrossWeight() );
                pstmt.setString(4, inventoryPSForm.getNoOfBoxes() );
                pstmt.setString(5, inventoryPSForm.getSplInstructions() );
                pstmt.setString(6, user.getUserName() );
                pstmt.setInt( 7, inventoryPSForm.getPackingSlipId() );
            	pstmt.executeUpdate();

                if (pstmt != null)
                {
                    pstmt.close();
                    pstmt = null;
                }

                pstmt = conn.prepareStatement( "DELETE FROM Inventory_PackingSlip_Lot_Table WHERE PackingSlip_Id = ? " );
                pstmt.setInt( 1, inventoryPSForm.getPackingSlipId() );
                pstmt.executeUpdate();

                if (pstmt != null)
                {
                    pstmt.close();
                    pstmt = null;
                }

                pstmt = conn.prepareStatement( "INSERT INTO Inventory_PackingSlip_Lot_Table( PackingSlip_Id, Lot_id, Ship_qty, WaferIds, Status ,Timestamp ) VALUES (?,?,?,?,?,CURRENT_TIMESTAMP)" );
            	for( LotDetails lotDetail:inventoryPSForm.getSelectedLotsList() )
            	{
            		if( lotDetail.isChecked() )
            		{
            			pstmt.setInt( 1, inventoryPSForm.getPackingSlipId() );
            			pstmt.setInt( 2, Integer.parseInt( lotDetail.getLotId() ) );
            			pstmt.setInt( 3, Integer.parseInt( lotDetail.getShipQty() ) );
            			pstmt.setString( 4, lotDetail.getCheckedWaferIdsAsString() );

            			pstmt.setString( 5, "ISSUED" );
            			pstmt.addBatch();
            		}
            	}
                pstmt.executeBatch();
            }
            

            status = true;
        }
        catch(Exception sql)
        {
            sql.printStackTrace();
            throw new ScalarException( "Could not Save Inventory Packing Slip " + inventoryPSForm.getPackingSlipNumber() );
        }
        finally
        {
            try
            {
                if (conn != null)
                {
                    if (status == true)
                    {                           
                        conn.commit();
                    }
                    else
                    {
                        conn.rollback();
                    }
                }
            }
            catch (SQLException ignore) {}
            if( rs != null)
            {
                try{ rs.close();}catch(SQLException se){}
            }
            if( pstmt != null)
            {
                try{ pstmt.close();}catch(SQLException se){}
            }
            if( conn != null)
            {
                try{ conn.close(); }catch(SQLException se){}
            }
        }
	}

	public static ArrayList<InventoryPackingSlip> searchPackingSlip( InventoryPackingSlipSearchForm inventoryPSSearchForm ) throws ScalarException
	{
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<InventoryPackingSlip> packingSlipList = new ArrayList<InventoryPackingSlip>();
        InventoryPackingSlip packingSlip = null;
    
        try 
        {
            conn = DataSource.getConnection();
            pstmt = conn.prepareCall ("{call SP_SEARCH_INVENTORY_PACKING_SLIP( ?,?,?,?,?,? )}");
            pstmt.setString(1, inventoryPSSearchForm.getSearchProcessType() );
            pstmt.setInt( 2, inventoryPSSearchForm.getSearchProcessStepId() );
            pstmt.setInt( 3, inventoryPSSearchForm.getSearchLocationId() );
            pstmt.setInt( 4, inventoryPSSearchForm.getSearchToVendorId() );
            pstmt.setString( 5, inventoryPSSearchForm.getSearchFromDate() );
            pstmt.setString( 6, inventoryPSSearchForm.getSearchToDate() );

            rs = pstmt.executeQuery();

            while( rs.next() ) 
            {
            	packingSlip = new InventoryPackingSlip();
            	packingSlip.setPackingSlipId( rs.getInt( "PackingSlip_Id" ) );
            	packingSlip.setPackingSlipNo( rs.getString( "PackingSlip_No" ) );
            	packingSlip.setFromVendor( rs.getString( "FROM_Location" ) );
            	packingSlip.setToVendor( rs.getString( "TO_Location" ) );
            	packingSlip.setShipDate( rs.getString( "Ship_Date" ) );
            	packingSlip.setStatus( rs.getString( "Status" ) );
            	packingSlip.setPsType( rs.getString( "PS_TYPE" ) );
            	packingSlipList.add( packingSlip );
            }
        }
        catch (Exception sqle) 
        {
            sqle.printStackTrace();
            throw new ScalarException ( "Could not fetch the Next Inventory Packing Slip Number" );
        }
        finally {
            if (rs != null) {
                try { rs.close(); } catch (SQLException excp)
                {
                    throw new ScalarException("SqlException Occurred ..");
                }
            }
            if (pstmt != null) {
                try { pstmt.close(); } catch (SQLException excp)
                {
                    throw new ScalarException("SqlException Occurred ..");

                }
            }
            if (conn != null) {
                try { conn.close(); } catch (SQLException excp)
                {
                    throw new ScalarException("SqlException Occurred ..");
                }
            }
        }
        return packingSlipList;
	}

    public static String getInventoryPSAsPDFFile(String host, InventoryPackingSlipForm packingSlipForm )
    {
		String fileXMLPath 		= null;
		String filePDFPath 		= null;
		String fileXSLTPath 	= null;
		FileWriter fWriter 		= null;
		File psPDFAttachment 	= null;
		File psXML 				= null;
        OutputStreamWriter out  = null;
        String psAsXML 			= formatAsXML( host, packingSlipForm );

		if( psAsXML == null )
		{
			return fileXMLPath;
		}

		try
		{
			String mailingTempDir 		= ConfigManager.getMailerTempDir();
			File tempDir 				= new File ( mailingTempDir ).getCanonicalFile();
			String psAttachmentFileName = packingSlipForm.getPackingSlipNumber();
			String xmlFileName 			= "Inventory_Packing_Slip_" + psAttachmentFileName + ".xml";
			String  xsltFileName		= ConfigManager.getInventoryPSXml2PdfXslFile();
			String psAttachmentPDFFileName = "Inventory_Packing_Slip_" + psAttachmentFileName + ".pdf";

			tempDir.mkdir();

			psXML = new File( tempDir.getCanonicalPath(), xmlFileName );
			psXML.deleteOnExit();

			psPDFAttachment = new File( tempDir.getCanonicalPath(), psAttachmentPDFFileName );
			psPDFAttachment.deleteOnExit();

			if( ( psXML.exists() == true ) || ( psXML.createNewFile() == true ) )
			{   				
                out = new OutputStreamWriter( new FileOutputStream( psXML ), "UTF-8" );

                out.write ( psAsXML );
                out.close ();
                out = null;


                fileXMLPath = psXML .getCanonicalPath() .toLowerCase();
				filePDFPath = psPDFAttachment .getCanonicalPath() .toLowerCase();
				boolean success = PDFGenerator.convertXML2PDF( fileXMLPath, xsltFileName, filePDFPath );
			}
		}
		catch( Exception e )
		{
			System.out.println( "Exception while creating packingslip PDF file");
			e.printStackTrace();
		}
		finally
		{
			if( fWriter != null )
			{
				try
				{
					fWriter.close();
					fWriter = null;
				}
				catch( IOException ignore ){}
			}
            if( out != null )
			{
				try
				{
					out.close();
					out = null;
				}
				catch( IOException ignore ){}
			}
        }

		return filePDFPath;
    }


	public static String formatAsXML ( String host, InventoryPackingSlipForm packingSlipForm ) {

		StringBuffer buf 			= new StringBuffer ( 2098 );
		String imagesDirLocation 	= ConfigManager.getChipTracImagesDir();
		String scalarLogo 			= ConfigManager.getScalarLogo();
		String crossCancel 			= ConfigManager.getCrossCanelImage();
		String SIGNATURE = "";

        try
		{
			 SIGNATURE = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.signature" );
		}
		catch ( NullPointerException e )
		{
            SIGNATURE =  Labels.DEFAULT_SIGNATURE_LABEL;
        }

        buf.append ( "<?xml version='1.0' encoding='UTF-8'?>\n" );

		if ( Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED.equalsIgnoreCase ( packingSlipForm.getStatus() ) )
		{
			buf.append ( "<InventorypackingSlip cancel='1'> \n" );
		}
		else
		{
			buf.append ( "<InventorypackingSlip cancel='0'> \n" );
		}

		buf.append ( "<images>\n" );
		buf.append ( "<logo>"+imagesDirLocation + scalarLogo +"</logo> \n" );
		buf.append ( "<cancelImage>"+imagesDirLocation+crossCancel+"</cancelImage> \n" );
		buf.append ( "</images>\n" );
		buf.append ( "<selfAddress> \n" );
        buf.append ( "<cName><![CDATA[" ) .append( packingSlipForm.getClientInfo().getClientName().toUpperCase() ) .append( "]]></cName> \n" );
        buf.append ( "<name><![CDATA[" ) .append( packingSlipForm.getClientInfo().getClientName() ) .append( "]]></name> \n" );
		buf.append ( packingSlipForm.getClientAddressXMLFormatted() );
		buf.append ( "</selfAddress> \n" );

		buf.append ( "<shipFromAddress> \n" );

		buf.append ( "<name><![CDATA[" ) .append( packingSlipForm.getFromVendorName() ) .append( "]]></name> \n" );
		buf.append ( packingSlipForm.getFromVendorAddressXMLFormatted() );
		buf.append ( "</shipFromAddress> \n" );

		buf.append ( "<shipToAddress> \n" );
        buf.append ( "<name><![CDATA[" ) .append( packingSlipForm.getToVendorName() ) .append( "]]></name> \n" );

		try
		{
			buf.append( packingSlipForm.getToVendorAddressXMLFormatted() );
		}
		catch (Exception e)
		{
			buf.append ( "<address1/> \n" );
			buf.append ( "<address2/> \n" );
			buf.append ( "<address3/> \n" );
			buf.append ( "<phone/> \n" );
			buf.append ( "<fax/> \n" );
			System.out.println(" Exception in formatAsXML: " +e);
		}
		buf.append ( "</shipToAddress> \n" );


        buf.append("<ShippingInstructions><![CDATA[");
        buf.append(((packingSlipForm.getSplInstructions() == null) ? "" : packingSlipForm.getSplInstructions().trim()));
        buf.append("]]></ShippingInstructions> \n");


        buf.append ( "<information> \n" );
		buf.append ( "<packingSlipNo><![CDATA[" ) .append ( (packingSlipForm.getPackingSlipNumber() == null) ? "" : packingSlipForm.getPackingSlipNumber() ) .append ("]]></packingSlipNo> \n");
		buf.append ( "<actualShipDate><![CDATA[" ) .append( (packingSlipForm.getShipDate() == null) ? "" : packingSlipForm.getShipDate() ) . append ( "]]></actualShipDate> \n" );


		buf.append ( "<wayBill><![CDATA[" ) .append ( (packingSlipForm.getWayBillNo() == null) ? "" : packingSlipForm.getWayBillNo() ) .append ( "]]></wayBill> \n" );
		buf.append ( "<cartons><![CDATA[" ) .append ( ( ( packingSlipForm.getNoOfBoxes() == null ) || ( packingSlipForm.getNoOfBoxes().equals("0") ) )? "" : packingSlipForm.getNoOfBoxes() ) .append ( "]]></cartons> \n" );
		buf.append ( "<grossWeight><![CDATA[" ).append (  packingSlipForm.getGrossWeight() ).append ( " ]]></grossWeight> \n" );

        buf.append ( "<signature><![CDATA[" ).append (  SIGNATURE ) .append ( " ]]></signature> \n" );

        buf.append ( "</information> \n" );

		buf.append ( "<lotDetails> \n" );


		LotDetails lotDetails 	= null;
		int size 				= packingSlipForm.getSelectedLotsList().size();

		for ( int i = 0; i < size; i++ )
		{
			lotDetails  = ( LotDetails ) packingSlipForm.getSelectedLotsList().get( i );

			String description	= "" ;
			
            buf.append ( "<lotInfo> \n" );

            buf.append ( "<mfgPartNumber><![CDATA[" ) .append ( lotDetails.getPartNumber() ) . append( "]]></mfgPartNumber>\n" );

            buf.append ( "<description><![CDATA[" );
            buf.append ( ( ( ( description == null ) || ( description.trim().length() == 0 ) ) ? "" : description.trim() ) );
            buf.append ( "]]></description>\n" );
            buf.append ( "<lotNumber><![CDATA[" ) .append ( ( ( lotDetails.getLotNumber() == null ) || ( lotDetails.getLotNumber().trim().length() == 0 ) ) ? "" : lotDetails.getLotNumber() ) .append ( "]]></lotNumber>\n" );
            buf.append ( "<fabLotNumber><![CDATA[" ) .append ( ( ( lotDetails.getFabLotNumber() == null ) || ( lotDetails.getFabLotNumber().trim().length() == 0 ) ) ? "" : lotDetails.getLotNumber() ) .append ( "]]></fabLotNumber>\n" );
            buf.append ( "<shipQty><![CDATA[" ) .append ( lotDetails.getShipQty() != null ? lotDetails.getShipQty() : "" ) .append ( "]]></shipQty>\n" );
            buf.append ( "<shipDieQty><![CDATA[" ) .append ( lotDetails.getShipDieQty() != null ? lotDetails.getShipDieQty() : "" ) .append ( "]]></shipDieQty>\n" );
            buf.append ( "<waferIds><![CDATA[" ) .append ( lotDetails.getCheckedWaferIdsAsString() != null ? lotDetails.getCheckedWaferIdsAsString() : "" ) .append ( "]]></waferIds>\n" );

			buf.append ( "</lotInfo>\n" );
		}

		buf.append ( "</lotDetails>\n" );
		buf.append ( "</InventorypackingSlip>\n" );
		return buf.toString();
	}
}
